package com.futvan.z.framework.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class NettyServer {


    public static void main(String[] args) {
        NettyServer nettyServer = new NettyServer();
    }

    public NettyServer(){
        //创建只处理请求连接的线程组-处理客户端的连接请求
        EventLoopGroup boss = new NioEventLoopGroup();

        //创建只处理客户端读写业务的线程组
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            //创建服务器端启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();

            //配置参数
            bootstrap.group(boss,worker)//配置线程组
                    //选择服务器的实现
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    //创建通道初始化的对象并配置该对象，向该对象中添加处理器来实现具体的业务处理
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //通过socketChannel获取对应管道
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new HttpServerCodec());//http编码解码器
                            pipeline.addLast(new NettyClientCloseListener());//监听关闭事件
                            pipeline.addLast(new HttpObjectAggregator(65536));//添加HTTP对象聚合处理器，用于将HTTP请求或响应中的多个消息片段聚合成完整的消息。
                            pipeline.addLast(new WebSocketServerProtocolHandler("/zsocket"));//websocket
                            pipeline.addLast(new NettyWebSocketHandler());//自定义消息处理
                        }

                    });

            //启动服务器,设置监听端口，设计为同步方式
            ChannelFuture channelFuture = bootstrap.bind(19820).sync();
            //监听关闭的channel,设置为同步方式
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            z.Error(e.getMessage());
        } finally {
            //断开所有链接
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
